package edu.utd.text.game.controller.commands;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Scanner;

import edu.utd.text.game.controller.Controller;
import edu.utd.text.game.domain.GameMap;

public class LoadGameCommand implements GameCommand {
	private String filename = "game.save";
	
	public String execute() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("This will overwrite the current game in memory.\n"
				+ "Are you sure you want to do that? (Y/N)");
		String response = scanner.nextLine().trim().toLowerCase();
		if (response.startsWith("y")) {
			; /* keep going */
		} else if (response.startsWith("n")) {
			return "Ok.";
		} else {
			return "That was a yes or no question...\n"
			+ "I'm not loading until you're sure that's what you want me to do.";
		}
		
		System.out.println("Enter the filename you want to load (default: \"" + this.filename + "\"):");
		String userFilename = scanner.nextLine().trim();
		if (userFilename.equals("") || userFilename.isEmpty()) {
			userFilename = this.filename; //if no input, use default
		}
		this.filename = userFilename;
		
		GameMap map;
		FileInputStream fis;
		ObjectInputStream in;
		
		try {
			fis = new FileInputStream(this.filename);
			in = new ObjectInputStream(fis);
			System.out.println("Reading save file: \"" + this.filename + "\"");
			map = (GameMap) in.readObject();
			//TODO: put logic in the controller to do this stuff.  That's where it belongs.
			Controller.INSTANCE.setGameMap(map);
			Controller.INSTANCE.getPlayer().setCurrentRoom(map.getMainRoom());
			return "Successfully loaded saved game map file: \"" + this.filename + "\"";
		} catch (IOException iox) {
			return "Error loading save file from disk.  Sorry.";
		} catch (ClassNotFoundException cnfx) {
			return "That seems to be a corrupt save file.  " + 
				"I found the file but I could not load the game map from it.";
		}
	}
	
}
